package bma.common.langutil.core;

import java.io.File;
import java.util.concurrent.Executors;

import junit.framework.TestCase;
import bma.common.langutil.concurrent.ScheduledExecutorJava;
import bma.common.langutil.io.FileMonitor;
import bma.common.langutil.io.FileMonitor.Event;
import bma.common.langutil.io.FileMonitorListener;
import bma.common.langutil.io.IOUtil;

public class FileMonitorTC extends TestCase {

	final org.slf4j.Logger log = org.slf4j.LoggerFactory
			.getLogger(FileMonitorTC.class);

	public void testEvent() throws Exception {

		File file = IOUtil.getUserDirFile("test.txt");
		if (file.exists()) {
			file.delete();
		}
		FileMonitor fm = new FileMonitor();
		fm.setExecutor(new ScheduledExecutorJava(Executors
				.newScheduledThreadPool(1)));
		fm.setFile(file.getPath());
		fm.setListener(new FileMonitorListener() {

			@Override
			public void handleEvent(String fileName, Event event) {
				log.info("{} - {}", fileName, event);
			}
		});
		fm.start();

		ObjectUtil.waitFor(this, 100);
		IOUtil.writeStringToFile(file, "test", "GBK");

		ObjectUtil.waitFor(this, 1500);
		IOUtil.writeStringToFile(file, "test2", "GBK");

		ObjectUtil.waitFor(this, 1500);
		file.delete();

		ObjectUtil.waitFor(this, 1500);
		fm.stop();
	}

}
